package com.link.base.base.wechat.service;

import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.util.Sha1Util;
import com.link.base.wechat.wxtoken.model.WxJsTicket;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 获取jssdk相关参数
 *
 * @author LiQun
 * @date 2019/3/12 10:14
 */
@Service
public class JssdkServiceImpl implements JssdkService {
    @Resource
    private WxTokenService wxTokenService;

    /**
     * 获取jssdk配置验证参数
     *
     * @author LiQun
     * @date 2019/3/12 10:15
     * @param appId 微信公众号的appid 用于获取jsticket
     * @param url 访问的地址url
     */
    @Override
    public Map<String, Object> getConfigParams(String appId ,String url) throws Exception {
        Map<String, Object> result = new HashMap<>(16);
        if (StringUtils.isBlank(appId)) {
            throw new ServiceException("WECHAT-009");
        }
        // 1.js_ticket
        WxJsTicket wxJsTicket = wxTokenService.getWxJsTicketByAppId(appId);
        if (wxJsTicket == null) {
            throw new Exception("WECHAT-010");
        }
        String jsapiTicket = wxJsTicket.getJs_ticket();
        // 2.随机字符串
        String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        // 3.时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        LCLogger.info().withMessage("原始url======>").withMessage(url).flush();
        // 4. url
        url = URLDecoder.decode(url,"UTF-8");

        // 5.将参数排序并拼接字符串
        String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        // 6.计算签名
        String signature = Sha1Util.getJsSHA1(str);

        result.put("noncestr", nonceStr);
        result.put("timestamp", timestamp);
        result.put("signature", signature);
        LCLogger.info().withMessage("url======>").withMessage(url).flush();
        LCLogger.info().withMessage("jsapi_ticket======>").withMessage(jsapiTicket).flush();
        LCLogger.info().withMessage("noncestr======>").withMessage(nonceStr).flush();
        LCLogger.info().withMessage("timestamp======>").withMessage(timestamp).flush();
        LCLogger.info().withMessage("signature======>").withMessage(signature).flush();
        return result;
    }
}
